package com.star.springai.chat.controller;

import lombok.extern.slf4j.Slf4j;

import com.star.springai.chat.models.ActorResource;
import com.star.springai.chat.tools.AlertTools;
import com.star.springai.chat.tools.DateTimeTools;
import reactor.core.publisher.Flux;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.ChatClientResponse;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.support.ToolCallbacks;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/chat")
public class ChatController {
    private final ChatClient chatClient;

    @Autowired
    private DateTimeTools dateTimeTools;
    @Autowired
    private AlertTools alertTools;
    @Autowired
    public ChatController(@Qualifier("enhancedChatClient") ChatClient chatClient) {
        this.chatClient = chatClient;
    }


    @GetMapping("/normal")
    public String normal(String message, String conversationId) {

        String response = chatClient.prompt()
                .user(message)
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, conversationId))
                .call()
                .content();


        log.info("Response: {}", response);
        return response;
    }

    @GetMapping("/formatResult")
    public ActorResource formatResult(String message) {

        return chatClient.prompt()
                .user(message)
                .call()
                .entity(ActorResource.class);
    }

    /**
     * 流式输出
     */
    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ChatClientResponse> stream(String message, String conversationId) {

        ToolCallback[] toolCallbacks = ToolCallbacks.from(dateTimeTools, alertTools);
        return chatClient.prompt()
                .user(message)
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, conversationId))
                .toolCallbacks(toolCallbacks)
                .stream().chatClientResponse();
    }

}
